<template>
  <div class="checkin-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-title">
        <h2>赛事检录管理</h2>
        <p>管理运动员比赛检录状态</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateCheckin" :loading="createLoading">
          <el-icon><Plus /></el-icon>
          创建检录记录
        </el-button>
        <el-button type="success" @click="handleBatchCheckin" :disabled="selectedCheckins.length === 0">
          <el-icon><Check /></el-icon>
          批量检录
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="比赛项目">
          <el-select 
            v-model="searchForm.eventId" 
            placeholder="请选择比赛项目"
            clearable
            style="width: 200px;"
            @change="handleSearch"
          >
            <el-option
              v-for="event in eventList"
              :key="event.id"
              :label="event.eventName"
              :value="event.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="运动员姓名">
          <el-input 
            v-model="searchForm.athleteName" 
            placeholder="请输入运动员姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="学号">
          <el-input 
            v-model="searchForm.studentNumber" 
            placeholder="请输入学号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="院系">
          <el-input 
            v-model="searchForm.department" 
            placeholder="请输入院系"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="检录状态">
          <el-select v-model="searchForm.checkinStatus" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option label="全部" :value="null"/>
            <el-option label="未检录" :value="0"/>
            <el-option label="已检录" :value="1"/>
            <el-option label="缺席" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息卡片 -->
    <div class="statistics-cards" v-if="searchForm.eventId">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.totalCount || 0 }}</div>
                <div class="stat-label">总人数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon checked-icon">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.checkedCount || 0 }}</div>
                <div class="stat-label">已检录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon unchecked-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.uncheckedCount || 0 }}</div>
                <div class="stat-label">未检录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon absent-icon">
                <el-icon><Close /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.absentCount || 0 }}</div>
                <div class="stat-label">缺席</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="checkinList"
        :loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="athleteName" label="运动员姓名" min-width="100" />
        
        <el-table-column prop="studentNumber" label="学号" width="120" />
        
        <el-table-column prop="raceNumber" label="参赛号" width="80" />
        
        <el-table-column prop="department" label="院系" min-width="120" />
        
        <el-table-column prop="className" label="班级" min-width="120" />
        
        <el-table-column prop="eventName" label="比赛项目" min-width="150" />
        
        <el-table-column prop="checkinStatus" label="检录状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusTagType(row.checkinStatus)"
              size="small"
            >
              {{ row.checkinStatusText }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="checkinTime" label="检录时间" width="160">
          <template #default="{ row }">
            {{ row.checkinTime ? formatDateTime(row.checkinTime) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="checkinOperator" label="检录员" width="100" />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                v-if="row.checkinStatus === 0"
                type="primary" 
                size="small" 
                @click="handleCheckin(row)"
              >
                检录
              </el-button>
              
              <el-button 
                v-if="row.checkinStatus === 0"
                type="warning" 
                size="small" 
                @click="handleMarkAbsent(row)"
              >
                缺席
              </el-button>
              
              <el-button 
                v-if="row.checkinStatus === 1"
                type="info" 
                size="small" 
                @click="handleCancelCheckin(row)"
              >
                取消检录
              </el-button>
              
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 检录对话框 -->
    <el-dialog 
      v-model="checkinDialogVisible" 
      title="运动员检录" 
      width="500px"
    >
      <el-form :model="checkinForm" :rules="checkinRules" ref="checkinFormRef" label-width="100px">
        <el-form-item label="运动员姓名">
          <el-input v-model="checkinForm.athleteName" disabled />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="checkinForm.studentNumber" disabled />
        </el-form-item>
        <el-form-item label="参赛号">
          <el-input v-model="checkinForm.raceNumber" disabled />
        </el-form-item>
        <el-form-item label="比赛项目">
          <el-input v-model="checkinForm.eventName" disabled />
        </el-form-item>
        <el-form-item label="运动员签名" prop="signatureImageUrl">
          <SignaturePad
            v-model="checkinForm.signatureImageUrl"
            title="运动员检录签名"
            :width="400"
            :height="200"
            @save="handleSignatureSave"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="checkinForm.notes" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="checkinDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmCheckin" :loading="checkinLoading">
          确认检录
        </el-button>
      </template>
    </el-dialog>

    <!-- 缺席对话框 -->
    <el-dialog 
      v-model="absentDialogVisible" 
      title="标记缺席" 
      width="400px"
    >
      <el-form :model="absentForm" ref="absentFormRef" label-width="80px">
        <el-form-item label="运动员">
          <span>{{ absentForm.athleteName }} ({{ absentForm.studentNumber }})</span>
        </el-form-item>
        <el-form-item label="缺席原因">
          <el-input 
            v-model="absentForm.notes" 
            type="textarea" 
            :rows="3"
            placeholder="请输入缺席原因"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="absentDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="handleConfirmAbsent" :loading="absentLoading">
          确认缺席
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Refresh, Check, Clock, Close, User
} from '@element-plus/icons-vue'
import SignaturePad from '@/components/SignaturePad.vue'
import {
  getCheckinPage,
  createCheckinRecords,
  checkinAthlete,
  batchCheckin,
  markAbsent,
  cancelCheckin,
  deleteCheckinRecord,
  getCheckinStatistics
} from '@/api/checkin'
import { getEventListSimple } from '@/api/event'

// 响应式数据
const loading = ref(false)
const createLoading = ref(false)
const checkinLoading = ref(false)
const absentLoading = ref(false)
const checkinList = ref([])
const eventList = ref([])
const selectedCheckins = ref([])
const statistics = ref({})

// 搜索表单
const searchForm = reactive({
  eventId: null,
  athleteName: '',
  studentNumber: '',
  department: '',
  checkinStatus: null
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 检录对话框
const checkinDialogVisible = ref(false)
const checkinForm = reactive({
  id: null,
  eventId: null,
  athleteId: null,
  registrationId: null,
  athleteName: '',
  studentNumber: '',
  raceNumber: '',
  eventName: '',
  signatureImageUrl: '',
  notes: ''
})

const checkinRules = {
  signatureImageUrl: [
    { 
      required: true, 
      message: '请进行签名', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '') {
          callback(new Error('请进行签名'))
        } else if (value === 'Invalid value.') {
          callback(new Error('签名数据无效，请重新签名'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 缺席对话框
const absentDialogVisible = ref(false)
const absentForm = reactive({
  id: null,
  athleteName: '',
  studentNumber: '',
  notes: ''
})

const checkinFormRef = ref()
const absentFormRef = ref()

// 注册组件
const components = {
  SignaturePad
}

// 计算属性
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning', // 未检录
    1: 'success', // 已检录
    2: 'danger'   // 缺席
  }
  return typeMap[status] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 处理签名保存
const handleSignatureSave = (signatureData) => {
  console.log('签名已保存:', signatureData ? '有签名数据' : '无签名数据')
  if (signatureData && signatureData.trim() !== '') {
    try {
      // 验证signatureData是否为有效的base64图片数据
      if (signatureData.startsWith('data:image/')) {
        // 创建JSON格式的签名数据
        const signatureJson = {
          imageData: signatureData,
          signTime: new Date().toISOString(),
          deviceInfo: navigator.userAgent.substring(0, 100), // 限制长度避免过长
          canvasWidth: 400,
          canvasHeight: 200,
          verified: true,
          version: '1.0'
        }
        
        // 将JSON数据转换为字符串存储
        const jsonString = JSON.stringify(signatureJson)
        console.log('生成的签名JSON长度:', jsonString.length)
        
        // 验证JSON长度，避免超过数据库限制
        if (jsonString.length > 65535) { // 65KB限制
          ElMessage.warning('签名数据过大，请使用较小的签名')
          return
        }
        
        checkinForm.signatureImageUrl = jsonString
      } else {
        console.error('无效的签名数据格式:', signatureData.substring(0, 50))
        ElMessage.error('签名数据格式无效，请重新签名')
      }
    } catch (error) {
      console.error('处理签名数据时出错:', error)
      ElMessage.error('处理签名数据时出错，请重新签名')
    }
  } else {
    checkinForm.signatureImageUrl = ''
  }
}

// 方法
const loadEventList = async () => {
  try {
    console.log('正在加载比赛项目列表...')
    const response = await getEventListSimple({ 
      status: 1,
      current: 1,
      size: 100 // 获取足够多的数据用于下拉选择
    })
    console.log('比赛项目API响应:', response)
    
    // 处理响应数据 - 后端返回的是分页数据格式
    if (response.data && response.data.records && Array.isArray(response.data.records)) {
      eventList.value = response.data.records
      console.log('成功加载比赛项目:', response.data.records.length, '个')
    } else if (response.data && Array.isArray(response.data)) {
      // 兼容简单数组格式
      eventList.value = response.data
      console.log('成功加载比赛项目:', response.data.length, '个')
    } else {
      eventList.value = []
      console.warn('比赛项目数据格式异常:', response.data)
    }
    
    if (eventList.value.length === 0) {
      ElMessage.warning('暂无比赛项目数据，请先添加比赛项目')
    }
  } catch (error) {
    console.error('加载比赛项目失败:', error)
    ElMessage.error('加载比赛项目失败: ' + (error.message || '未知错误'))
    eventList.value = []
  }
}

const loadCheckinList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await getCheckinPage(params)
    const { records, total } = response.data
    
    checkinList.value = records || []
    pagination.total = total || 0
  } catch (error) {
    console.error('加载检录列表失败:', error)
    ElMessage.error('加载检录列表失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  if (!searchForm.eventId) return
  
  try {
    const response = await getCheckinStatistics(searchForm.eventId)
    statistics.value = response.data || {}
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadCheckinList()
  loadStatistics()
}

const handleReset = () => {
  Object.assign(searchForm, {
    eventId: null,
    athleteName: '',
    studentNumber: '',
    department: '',
    checkinStatus: null
  })
  statistics.value = {}
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  handleSearch()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedCheckins.value = selection
}

const handleCreateCheckin = async () => {
  if (!searchForm.eventId) {
    ElMessage.warning('请先选择比赛项目')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要为当前比赛项目创建检录记录吗？',
      '确认创建',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    createLoading.value = true
    await createCheckinRecords(searchForm.eventId)
    ElMessage.success('检录记录创建成功')
    handleSearch()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('创建检录记录失败:', error)
      ElMessage.error('创建检录记录失败')
    }
  } finally {
    createLoading.value = false
  }
}

const handleCheckin = (row) => {
  Object.assign(checkinForm, {
    id: row.id,
    eventId: row.eventId,
    athleteId: row.athleteId,
    registrationId: row.registrationId,
    athleteName: row.athleteName,
    studentNumber: row.studentNumber,
    raceNumber: row.raceNumber,
    eventName: row.eventName,
    signatureImageUrl: '',
    notes: ''
  })
  checkinDialogVisible.value = true
}

const handleConfirmCheckin = async () => {
  if (!checkinFormRef.value) return

  try {
    await checkinFormRef.value.validate()
    
    checkinLoading.value = true
    
    const data = {
      eventId: checkinForm.eventId,
      athleteId: checkinForm.athleteId,
      registrationId: checkinForm.registrationId,
      checkinStatus: 1,
      signatureImageUrl: checkinForm.signatureImageUrl,
      notes: checkinForm.notes
    }
    
    await checkinAthlete(data)
    ElMessage.success('检录成功')
    checkinDialogVisible.value = false
    handleSearch()
  } catch (error) {
    console.error('检录失败:', error)
    ElMessage.error('检录失败')
  } finally {
    checkinLoading.value = false
  }
}

const handleBatchCheckin = async () => {
  if (selectedCheckins.value.length === 0) {
    ElMessage.warning('请选择要检录的运动员')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量检录选中的 ${selectedCheckins.value.length} 名运动员吗？`,
      '确认批量检录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const checkinIds = selectedCheckins.value.map(item => item.id)
    await batchCheckin(checkinIds)
    ElMessage.success('批量检录成功')
    handleSearch()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量检录失败:', error)
      ElMessage.error('批量检录失败')
    }
  }
}

const handleMarkAbsent = (row) => {
  Object.assign(absentForm, {
    id: row.id,
    athleteName: row.athleteName,
    studentNumber: row.studentNumber,
    notes: ''
  })
  absentDialogVisible.value = true
}

const handleConfirmAbsent = async () => {
  try {
    absentLoading.value = true
    await markAbsent(absentForm.id, absentForm.notes)
    ElMessage.success('标记缺席成功')
    absentDialogVisible.value = false
    handleSearch()
  } catch (error) {
    console.error('标记缺席失败:', error)
    ElMessage.error('标记缺席失败')
  } finally {
    absentLoading.value = false
  }
}

const handleCancelCheckin = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该运动员的检录状态吗？',
      '确认取消检录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await cancelCheckin(row.id)
    ElMessage.success('取消检录成功')
    handleSearch()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消检录失败:', error)
      ElMessage.error('取消检录失败')
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条检录记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )

    await deleteCheckinRecord(row.id)
    ElMessage.success('删除成功')
    handleSearch()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadEventList()
  loadCheckinList()
})
</script>

<style scoped>
.checkin-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title h2 {
  margin: 0;
  color: #303133;
}

.header-title p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card, .table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
}

.total-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.checked-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.unchecked-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.absent-icon {
  background: linear-gradient(135deg, #fc466b 0%, #3f5efb 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .statistics-cards .el-col {
    margin-bottom: 16px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
